package com.itheima.dfs;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dfs")
@Slf4j
public class FileController {
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    //注入远程调用接口
    @Autowired
    private WmMaterialFeign wmMaterialFeign;

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile multipartFile) {

        //获取请求的来源
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        //判断是否为空
        if (StringUtils.isEmpty(from)) {
            throw new LeadNewsException("非法请求，拒绝上传！");
        }
        //获取源文件的名字--为了拿到文件后缀名
        String filename = multipartFile.getOriginalFilename();
        log.info("上传的文件名：{}", filename);
        //获取文件的后缀名
        String extension = StringUtils.getFilenameExtension(filename);
        try {
            //上传文件到fastdfs
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(),
                    extension, null);
            //得到文件的url
            String fileId = storePath.getFullPath();
            log.debug("上传文件的url路径：{}", fileId);
            //远程调用自媒体微服务--保存到素材库
            //校验来源，通过则保存到素材库--WEMEDIA_PIC自媒体端上传过来的图片
            if (SystemConstants.WEMEDIA_PIC.equals(from)) {
                addWmMaterial(fileId);
            }
            //拼接完整路径返回给前端
            return ResultVo.ok(Collections.singletonMap("url",
                    fdfsWebServer.getWebServerUrl() + fileId));
        } catch (IOException e) {
            log.error("上传文件失败", e);
        }
        return ResultVo.bizError("上传文件失败！");
    }

    @GetMapping("/delete/{id}")
    public ResultVo delete(@PathVariable Long id) {
        //获取请求的来源
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if (StringUtils.isEmpty(from)) {
            throw new LeadNewsException("非法请求，拒绝删除");
        }
        //远程调用查询数据库获取url
        ResultVo<WmMaterial> resultVo = wmMaterialFeign.selectById(id);
        WmMaterial wmMaterial = resultVo.getData();
        if (StringUtils.isEmpty(wmMaterial)) {
            throw new LeadNewsException(HttpCodeEnum.DATA_NOT_EXIST);
        }
        Long userId = Long.parseLong(RequestContextUtil.getUserId());
        if (SystemConstants.WEMEDIA_PIC.equals(from)) {
            if(wmMaterialFeign.delete(id,userId).isSuccess()){
                String url = wmMaterial.getUrl();
                client.deleteFile(url);
                return ResultVo.ok();
            }
        }
        return ResultVo.error();
    }

    /**
     * 远程调用自媒体微服务，添加素材
     *
     * @param fileId
     */
    private void addWmMaterial(String fileId) {
        //构建WmMaterial对象
        log.info("上传文件的url路径：{}", fileId);
        WmMaterial wmMaterial = new WmMaterial();
        //设置参数
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(Long.parseLong(RequestContextUtil.getUserId()));
        wmMaterial.setType(BusinessConstants.WmMaterialConstants.TYPE_PIC);

        wmMaterial.setIsCollection(0);
        wmMaterial.setCreatedTime(LocalDateTime.now());
        //远程调用
        ResultVo result = wmMaterialFeign.add(wmMaterial);

        //判断是否成功
        if (!result.isSuccess()) {
            throw new LeadNewsException("文件上传，添加素材失败");
        }
        log.info("添加素材成功");
    }

    /**
     * 批量下载文件
     * @param fileIds
     * @return
     */
    @PostMapping("/download")
    ResultVo<List<byte[]>> download(@RequestBody List<String> fileIds){
        //判断是否有内容
        if(!CollectionUtils.isEmpty(fileIds)){
            //创建字节数组处理器
            DownloadByteArray dba = new DownloadByteArray();

            List<byte[]> list = fileIds.stream().map(fileId -> {
                //解析图片地址
                StorePath storePath = StorePath.parseFromUrl(fileId);
                //下载文件封装进字节数组
                byte[] bytes = client.downloadFile(storePath.getGroup(), storePath.getPath(), dba);
                return bytes;
            }).collect(Collectors.toList());
            return ResultVo.ok(list);
        }
        return ResultVo.ok();
    }


}
